package com.business_clean.ui.activity.personnel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.R;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseActivity;
import com.business_clean.app.config.Constant;
import com.business_clean.app.ext.LoadingDialogExtKt;
import com.business_clean.app.uitl.ActivityForwardUtil;
import com.business_clean.app.uitl.ImageCompressor;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.UploadFileHelper;
import com.business_clean.data.mode.members.IDCardMemberEntity;
import com.business_clean.databinding.ActivitySignHandBinding;
import com.business_clean.ui.activity.custom.AddProjectActivity;
import com.business_clean.viewmodel.request.ProjectMembersViewModel;
import com.business_clean.viewmodel.request.ProjectPersonnelViewModel;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import me.hgj.mvvmhelper.base.BaseViewModel;
import me.hgj.mvvmhelper.base.Ktx;
import me.hgj.mvvmhelper.ext.AppExtKt;
import me.hgj.mvvmhelper.ext.LogExtKt;

public class SignHandActivity extends BaseActivity<ProjectMembersViewModel, ActivitySignHandBinding> {

    private String uuid;

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        if (getIntent() != null && getIntent().getExtras() != null) {
            uuid = getIntent().getExtras().getString("uuid");
        }
    }

    @Override
    public void onBindViewClick() {
        //完成
        mDatabind.tvSignHandFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                XXPermissions.with(SignHandActivity.this)
                        .permission(Permission.WRITE_EXTERNAL_STORAGE)
                        .request(new OnPermissionCallback() {
                            @Override
                            public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                                if (allGranted) {
                                    uploadHandBitmap();
                                }
                            }
                        });

            }
        });
        //关闭当前界面
        mDatabind.tvSignHandClean.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDatabind.hand.redo();
            }
        });
        //清空界面
        mDatabind.tvSignHandClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void uploadHandBitmap() {
        if (mDatabind.hand.getBitmap() == null) {
            ToastUtil.show("请签名");
            return;
        }
        File handFile = saveBitmapToFile(mDatabind.hand.getBitmap(), "sign_hand_" + TimeUtils.getNowMills());//存储到内部路径  每次都覆盖
        if (handFile == null) {
            ToastUtil.show("图片保存异常，请重新尝试");
            return;
        }
        ImageCompressor.compressBitmap(this, handFile.getAbsolutePath(), 10, new OnKeyValueResultCallbackListener() {
            @Override
            public void onCallback(String srcPath, String resultPath) {
                UploadFileHelper.getInstance().uploadPictures(SignHandActivity.this, resultPath, UploadFileHelper.PATH_HEADER_PERSONNEL, new UploadFileHelper.UploadListener() {
                    @Override
                    public void onUploadSuccess(String response) {
                        HashMap<String, String> hashMap = new HashMap<>();
                        hashMap.put("op_type", "approve");
                        hashMap.put("uuid", uuid);
                        hashMap.put("sign_pic", "" + response);
                        mViewModel.requestUpdateMembers(hashMap, AddProjectActivity.ID_SIGN_HAND, 1);
                    }

                    @Override
                    public void onUploadFailed(String error) {
                        ToastUtil.show(error);
                    }

                    @Override
                    public void onUploadProgress(int progress) {

                    }
                });
            }
        });
    }

    @Override
    public void onRequestSuccess() {
        mViewModel.getUpdateSignHandStatus().observe(this, new Observer<IDCardMemberEntity>() {
            @Override
            public void onChanged(IDCardMemberEntity idCardMemberEntity) {
                ToastUtil.showLong("入职信息将在审批通过后生效，请前往“待办”查看");
                App.appViewModelInstance.getRefreshMember().setValue(true);
                AppExtKt.finishActivity(SignHandActivity.class);
                AppExtKt.finishActivity(AddProjectActivity.class);
            }
        });
    }

    /**
     * 存储图片到本地  路径是内部路径 不对外开放
     *
     * @param bitmap
     * @param fileName
     * @return
     */
    private File saveBitmapToFile(Bitmap bitmap, String fileName) {
        // 获取外部存储目录
        File externalFilesDir = new File(Constant.INTERNAL_SIGN_HAND_PATH);

        File signHandDir = new File(externalFilesDir, "sign-hand");
        if (!signHandDir.exists()) {
            signHandDir.mkdirs();
        }

        // 创建目标文件
        File file = new File(signHandDir, fileName + ".png");

        try {
            // 创建输出流
            FileOutputStream fos = new FileOutputStream(file);

            // 将Bitmap压缩为PNG格式并写入文件
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

            // 关闭流
            fos.close();

            return file; // 返回保存的文件对象
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

}